<template>
  <div class="cmt-box">
    <div class="flex-row" name="textarea">
      <a class="flex-item-start mr-2">
        <img
          class="profile-sm"
          :src="user.avatar ? user.avatar : avatar"
          :alt="user.name ? user.name : '头像'"
        />
      </a>
      <div class="textarea-box">
        <div class="textarea-wrap">
          <el-input
            type="textarea"
            placeholder="评论一下"
            v-model="comment_content"
            maxlength="300"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 5 }"
            @keyup.native.enter.ctrl="subComment"
          ></el-input>
        </div>
        <div class="textarea-bottom">
          <span>Ctrl + Enter</span>
          <button class="x-btn" @click="subComment">提交评论</button>
        </div>
      </div>
    </div>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(cmt, index) in comments" :key="index">
        <div class="cmt-info">
          <a class="avatar mr-2">
            <img class="profile-sm" :src="cmt.fromAvatar" alt="" />
          </a>
          <div class="right">
            <a href="" class="name">{{ cmt.fromName }}</a>
            <br/>
            <span class="date">{{ format(cmt.createTime) }}</span>
          </div>
        </div>
        <div class="cmt-content">{{ cmt.content }}</div>
        <div class="control">
          <span :class="[cmt.liked ? 'cliked' : '']" @click="likeClick(cmt)">
            <i class="layui-icon layui-icon-praise"></i>
            <span>{{ cmt.hits }}</span>
          </span>
          <span @click="showReplyBox(cmt, cmt)">
            <i class="layui-icon layui-icon-dialogue"></i>
            <span>{{ cmt.replies.length }}</span>
          </span>
        </div>
        <!-- 回复列表 -->
        <div class="reply-list">
          <div
            class="reply-item"
            v-for="(reply, index) in cmt.replies"
            :key="index"
          >
            <div class="reply-info">
              <a href="" class="name">
                <strong>{{ reply.fromName }}</strong>
              </a>
              <span>：@</span>
              <span>{{ reply.toName }}</span>
            </div>
            <div class="cmt-content">
              {{ reply.content }}
            </div>
            <div class="control">
              <span>{{ format(reply.createTime) }}</span>
              <span
                :class="[reply.liked ? 'cliked' : '']"
                @click="likeClick(reply)"
              >
                <i class="layui-icon layui-icon-praise"></i>
                <span>{{ reply.hits }}</span>
              </span>
              <span @click="showReplyBox(cmt, reply)">
                <i class="layui-icon layui-icon-dialogue"></i>
              </span>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <transition name="fade">
          <div class="input-wrapper" v-if="showCmtId === cmt.id">
            <el-input
              v-model="reply_content"
              type="textarea"
              autofocus
              maxlength="300"
              show-word-limit
              :autosize="{ minRows: 2, maxRows: 4 }"
              :placeholder="placeholder"
              @keyup.native.enter.ctrl="subReply(cmt)"
            >
            </el-input>
            <div class="btn-container-right">
              <button type="button" class="x-btn x-btn-primary" @click="cancel">
                取消
              </button>
              <button type="button" class="x-btn" @click="subReply(cmt)">
                确定
              </button>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { formatTime, parseTime } from "@/utils";
import { Message } from "element-ui";
import request from "@/utils/request";

export default {
  name: "Comment",
  props: ["cmt"],
  data() {
    return {
      avatar: require("@/assets/default.jpg"),
      // 评论的内容
      comment_content: "",
      // 回复的内容
      reply_content: "",
      // 被回复的人
      to: "",
      placeholder: "请输入回复内容",
      showCmtId: "",
      comments: []
    };
  },
  computed: {
    user() {
      return this.$store.getters.user;
    },
    logged() {
      return this.$store.getters.token;
    },
  },
  methods: {
    getComments() {
      request.get(`/comment/${this.cmt.type}?id=${this.cmt.id}`).then((res) => {
        this.comments = res.data;
      });
    },
    /**
     * 提交评论
     */
    subComment() {
      // 判断是否登录
      if (this.logged == null) {
        Message({
          type: "info",
          message: "登录后才能发表评论~",
          center: true,
          duration: 1500,
        });
        return;
      }
      // 判断内容是否为空
      if (this.comment_content.trim() === "") {
        return;
      }
      let comment = {
        articleId: this.cmt.id,
        fromId: this.user.uid,
        fromName: this.user.name,
        fromAvatar: this.user.avatar,
        content: this.comment_content,
        createTime: new Date().getTime(),
        liked: false,
        hits: 0,
        replies: [],
      };
      this.comments.push(comment);
      this.comment_content = "";
      // 发送请求
      request.post(`/comment/${this.cmt.type}/saveOrUpdate`, comment).then((res) => {});
    },
    /**
     * 点赞
     */
    likeClick(cmt) {
      //   console.log(cmt.liked);
      cmt.hits = cmt.liked ? --cmt.hits : ++cmt.hits;
      cmt.liked = !cmt.liked;
    },
    /**
     * 格式化时间
     */
    format(time) {
      //   console.log(time);
      if (typeof time == "number") {
        return formatTime(time);
      } else {
        return parseTime(time);
      }
    },

    /**
     * 显示回复框
     */
    showReplyBox(cmt, reply) {
      this.to = reply;
      this.placeholder = "@" + reply.fromName;
      this.showCmtId = cmt.id;
    },
    /**
     * 取消回复
     */
    cancel() {
      this.showCmtId = "";
      this.placeholder = "请输入回复内容";
    },
    /**
     * 提交回复
     */
    subReply(cmt) {
      // 判断是否登录
      if (this.logged == null) {
        Message({
          type: "info",
          message: "登录后才能发表评论~",
          center: true,
          duration: 1500,
        });
        return;
      }
      // 判断内容是否为空
      if (this.reply_content.trim() === "") {
        return;
      }
      let reply = {
        commentId: cmt.id,
        fromId: this.user.uid,
        fromName: this.user.name,
        fromAvatar: this.user.avatar,
        toId: this.to.fromId,
        toName: this.to.fromName,
        toAvatar: this.to.fromAvatar,
        content: this.reply_content,
        liked: false,
        hits: 0,
        createTime: new Date().getTime(),
      };
      this.comments.find((c) => c.id === cmt.id).replies.push(reply);
      this.showCmtId = "";
      this.reply_content = "";
      // 发送请求
      request.post(`/reply/${this.cmt.type}/saveOrUpdate`, reply).then((res) => {});
    },
  },
  created() {
    this.getComments();
  }
};
</script>

<style scope>
.cmt-box {
  margin-top: 2rem;
}
.cmt-box textarea {
  max-height: 200px;
}
.flex-row {
  background-color: #fff;
  padding: 15px;
}
.textarea-box {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}
.textarea-bottom {
  margin-top: 15px;
  text-align: right;
}
.textarea-bottom span {
  color: #ddd;
  margin-right: 10px;
}

.cmt-list {
  margin-top: 15px;
}
.cmt-list .cmt-item + .cmt-item {
  border-top: 1px solid #f8f8f8;
  /* margin-top: 5px; */
}

.cmt-item {
  padding: 15px;
  background-color: #fff;
}
.cmt-item span {
  color: #999;
  font-size: 0.8px;
}
.cmt-item .cmt-info .avatar {
  display: inline-block;
  vertical-align: bottom;
}
.cmt-item .cmt-info .right {
  display: inline-block;
}
.cmt-item .name {
  color: #5fb878;
}
.cmt-item .cmt-content {
  margin: 10px 0;
  font-size: 14px;
  text-align: justify;
}
.cmt-item .cmt-content,
.cmt-item .control {
  padding-left: 1rem;
}
.cmt-item .control > span {
  cursor: pointer;
}
.cmt-item .control > span + span {
  margin-left: 10px;
}
.cliked {
  color: #5fb878 !important;
}

.reply-list {
  padding: 0 0.8rem;
  background-color: #f8f8f8;
  border-left: 4px solid #5fb878;
  border-radius: 2px;
  margin-left: 1rem;
  margin-top: 1rem;
}
.reply-list .reply-item {
  padding: 0.8rem 0;
}
.reply-list .reply-item + .reply-item {
  border-top: 1px solid #fff;
}

.input-wrapper {
  padding: 1rem;
}
.btn-container-right {
  text-align: right;
  padding: 10px 0;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>